using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;

namespace ClubWebsite
{
    public partial class Default : System.Web.UI.MasterPage
    {
        public delegate void SaveChangesClickedEventHandler();
        public event SaveChangesClickedEventHandler SaveChangesClicked;

        private Guid _clubID = Guid.Empty;
        public Guid ClubID
        {
            get
            {
                if (_clubID == Guid.Empty)
                {
                    if (Request.Url.ToString().ToLower().Contains("club.aspx?id="))
                    {
                        _clubID = new Guid(Regex.Match(Request.Url.ToString(), @"(?<=Club\.aspx\?ID=).*").Value);
                    }
                    else if ((Request.QueryString["Club"] is string) && (Request.QueryString["Club"].Trim().Length > 0))
                    {
                        _clubID = Functions.GetDatabaseDataContext()
                            .DBClubs
                            .Where(c => c.UniqueTextForURLs.ToLower() == Request.QueryString["Club"].ToLower())
                            .Select(c => c.ID)
                            .FirstOrDefault();
                    }
                    else
                    {
                        _clubID = Functions.GetDatabaseDataContext()
                            .DBClubs
                            .Where(c => c.Domain.ToLower() == Request.Url.Host.Replace("www", "").Trim('.').ToLower())
                            .Select(c => c.ID)
                            .FirstOrDefault();
                    }
                }
                return _clubID;
            }
        }

        private Guid _pageID = Guid.Empty;
        public Guid PageID
        {
            get
            {
                if (_pageID == Guid.Empty)
                {
                    if (Request.Url.ToString().ToLower().Contains("page.aspx?id="))
                    {
                        _pageID = new Guid(Regex.Match(Request.Url.ToString(), @"(?<=Page\.aspx\?ID=).*").Value);
                    }
                    else if ((Request.QueryString["Page"] is string) && (Request.QueryString["Page"].Trim().Length > 0))
                    {
                        _pageID = Functions.GetDatabaseDataContext()
                            .DBPages
                            .Where(p => (p.UniqueTextForURLs.ToLower() == Request.QueryString["Page"].ToLower()) && (p.Club.ID == ClubID))
                            .Select(p => p.ID)
                            .FirstOrDefault();
                        if (_pageID == Guid.Empty)
                        {
                            if (Request.QueryString["Page"].Length == 32)
                            {
                                // Assume the page's GUID was passed
                                _pageID = new Guid(Request.QueryString["Page"]);
                            }
                            else
                            {
                                // Page not found
                                throw new HttpException(404, "Sorry, the page could not be found.");
                            }
                        }
                    }
                    else
                    {
                        // Redirect to the default page for the club if possible
                        if ((Request.RawUrl.ToLower().Contains("default.aspx")) || (!(Request.Path.ToLower().Contains("."))))
                        {
                            using (MainDataClassesDataContext databaseDataContext = Functions.GetDatabaseDataContext())
                            {
                                _pageID = databaseDataContext
                                    .DBClubs
                                    .Where(c => c.ID == ClubID)
                                    .Select(c => c.DefaultPageID)
                                    .Single();
                                if (_pageID != Guid.Empty)
                                {
                                    string pageUniqueTextForURLs = databaseDataContext
                                        .DBPages
                                        .Where(p => p.ID == _pageID)
                                        .Select(p => p.UniqueTextForURLs)
                                        .Single();
                                    Response.Redirect(String.Format("{0}/", pageUniqueTextForURLs));
                                }
                            }
                        }
                    }
                }
                return _pageID;
            }
        }

        private string _pageTitle = null;
        public string PageTitle
        {
            get
            {
                if (_pageTitle == null)
                {
                    using (MainDataClassesDataContext databaseDataContext = Functions.GetDatabaseDataContext())
                    {
                        string club = databaseDataContext
                            .DBClubs
                            .Where(c => c.ID == ClubID)
                            .Select(c => c.Name)
                            .FirstOrDefault();
                        string page = "";
                        if (PageID != Guid.Empty)
                        {
                            page = databaseDataContext
                                .DBPages
                                .Where(p => p.ID == PageID)
                                .Select(p => p.Title)
                                .FirstOrDefault();
                            if (page == null)
                            {
                                page = "New page";
                            }
                        }
                        if ((page == null) || (page.Trim().Length == 0))
                        {
                            page = "Untitled";
                        }
                        bool pageIsClubDefault = databaseDataContext
                            .DBClubs
                            .Any(c => (c.DefaultPageID == PageID) && (c.ID == ClubID));
                        if (pageIsClubDefault)
                        {
                            _pageTitle = club;
                        }
                        else
                        {
                            _pageTitle = String.Format("{0} - {1}", club, page);
                        }
                    }
                }
                return _pageTitle.Trim();
            }
        }

        public StateBag CurrentViewState
        {
            get
            {
                return ViewState;
            }
        }
        public ScriptManager ScriptManager
        {
            get
            {
                return ScriptManager1;
            }
        }

        public string DefaultButton
        {
            set
            {
                form1.DefaultButton = value;
            }
        }

        protected void Page_Init()
        {
            // Display the club's template
            if (!IsPostBack)
            {
                // Create a folder for the club and place the default CSS in it
                System.IO.DirectoryInfo clubDirectoryInfo = new System.IO.DirectoryInfo(MapPath("/Files/") + ClubID);
                if (!clubDirectoryInfo.Exists)
                {
                    clubDirectoryInfo.Create();
                }

                using (MainDataClassesDataContext databaseDataContext = Functions.GetDatabaseDataContext())
                {
                    var clubProperties = databaseDataContext
                        .DBClubs
                        .Where(c => c.ID == ClubID)
                        .Select(c => new { c.DescriptionForSearchEngines, 
                            c.KeywordsForSearchEngines, 
                            c.TemplateHTML, 
                            c.GoogleAnalyticsTrackingCode,
                            c.CSS
                        })
                        .Single();

                    // Ensure the CSS file is up-to-date
                    System.IO.FileInfo clubCssFileInfo = new System.IO.FileInfo(clubDirectoryInfo.FullName + "/Default.css");
                    string clubCss = clubProperties.CSS;
                    string clubFileCss = null;
                    if (clubCssFileInfo.Exists)
                    {
                        using (System.IO.StreamReader clubCssStreamReader = new System.IO.StreamReader(clubCssFileInfo.FullName))
                        {
                            clubFileCss = clubCssStreamReader.ReadToEnd();
                        }
                    }
                    if (clubFileCss != clubCss)
                    {
                        using (System.IO.StreamWriter clubCssStreamWriter = new System.IO.StreamWriter(clubCssFileInfo.FullName))
                        {
                            clubCssStreamWriter.Write(clubCss.Trim());
                            clubCssStreamWriter.Close();
                        }
                    }
                    Head.Text += "<link rel=\"stylesheet\" type=\"text/css\" href=\"/Files/" + ClubID + "/Default.css\" />\r\n";

                    // Add favicon if it exists
                    if (System.IO.File.Exists(clubDirectoryInfo.FullName + "/favicon.ico"))
                    {
                        Head.Text += "<link rel=\"shortcut icon\" type=\"image/vnd.microsoft.icon\" href=\"/Files/" + ClubID + "/favicon.ico\" />\r\n";
                        Head.Text += "<link rel=\"icon\" type=\"image/vnd.microsoft.icon\" href=\"/Files/" + ClubID + "/favicon.ico\" />\r\n";
                    }

                    string description = clubProperties.DescriptionForSearchEngines;
                    if ((description is string) && (description.Trim().Length > 0))
                    {
                        Head.Text += "<meta name=\"description\" content=\"" + HttpUtility.HtmlEncode(description.Trim()) + "\" />\r\n";
                    }

                    string keywords = clubProperties.KeywordsForSearchEngines;
                    if ((keywords is string) && (keywords.Trim().Length > 0))
                    {
                        Head.Text += "<meta name=\"keywords\" content=\"" + HttpUtility.HtmlEncode(keywords.Trim()) + "\" />\r\n";
                    }

                    string templateHTML = clubProperties.TemplateHTML;
                    if (!(templateHTML is string) || (templateHTML.Trim().Length == 0))
                    {
                        templateHTML = databaseDataContext
                            .Settings
                            .Select(s => s.ClubDefaultTemplateHTML)
                            .Single();
                    }
                    string content = Functions.ConvertTextWithTagsIntoHTML(templateHTML, this);
                    Functions.ConvertTextWithTagsIntoControls(content.Substring(0, content.IndexOf("[pagecontent]", StringComparison.CurrentCultureIgnoreCase)), plhContentStart, Page, false);
                    Functions.ConvertTextWithTagsIntoControls(content.Substring(content.IndexOf("[pagecontent]", StringComparison.CurrentCultureIgnoreCase) + "[pagecontent]".Length), plhContentEnd, Page, false);

                    // Set the folder to store files for the current page
                    Session["FCKeditor:UserFilesPath"] = "/Files/" + ClubID + "/";
                    Application["FCKeditor:UserFilesPath"] = "/Files/" + ClubID + "/";

                    // Set the Google Analytics tracking code
                    string googleAnalyticsTrackingCode = clubProperties.GoogleAnalyticsTrackingCode;
                    if ((!(googleAnalyticsTrackingCode is string)) || (googleAnalyticsTrackingCode.Trim().Length == 0))
                    {
                        googleAnalyticsTrackingCode = databaseDataContext
                            .DBClubs
                            .Where(c => c.ID == Guid.Empty)
                            .Select(c => c.GoogleAnalyticsTrackingCode)
                            .Single();
                    }
                    GoogleAnalyticsTrackingCode.Text = googleAnalyticsTrackingCode;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set the page title
                Page.Header.Title = PageTitle;
            }
        }

        public void EditPageOption_SaveChangesClicked()
        {
            if (SaveChangesClicked != null)
            {
                SaveChangesClicked();
            }
            Session.Remove("EditPage");
            Response.Redirect(Request.RawUrl.ToString());
        } 
    }
}
